package TestATM;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public class FileOperation {

    public static HashMap<String, UserInfo> readFile() {
        //1、产生一个Properties对象
        Properties props = new Properties();
        //2、调用Properties的load方法读取文件
        try {
            props.load(new FileInputStream("user.properties"));//4条记录已存在
        } catch (IOException e) {
            e.printStackTrace();
        }
        //3、再把Properties中的数据转存到一个HashMap中
        HashMap<String, UserInfo> allUsers = new HashMap<>();

        Set<Object> keySet = props.keySet();//根据键值遍历map集合
        for (Object key : keySet) {
            String k = (String) key;
            String value = props.getProperty(k);//每条记录
            String[] vArray = value.split("[-]");
            UserInfo v = new UserInfo(vArray[0], vArray[1], Double.parseDouble(vArray[2]));
            allUsers.put(k, v);
        }

/*        String info = "";
        for (Object o : set) {
            String key = (String) o;
            String value = props.getProperty(key);
            info += value + ";";
        }
        info = info.substring(0, info.length() - 1);

        String[] str = info.split("[;]");
        for (int i = 0; i < str.length; i++) {
            String[] s = str[i].split("[-]");
            map.put(s[0], new UserInfo(s[0], s[1], Double.parseDouble(s[2])));
        }*/
        //4、最后返回Map
        return allUsers;
    }

    public static void writeFile(HashMap<String, UserInfo> allUsers) {
        //1、把HashMap中的数据转存到Properties当中；
        Properties props = new Properties();//产生一个集合对象
        Set<String> keySet = allUsers.keySet();
        for (String s : keySet) {
            UserInfo userInfo = allUsers.get(s);
            //System.out.println(userInfo);
            String info = userInfo.toString();//将对象转换成字符串
            props.setProperty(s, info);
        }
        //2、调用Properties的store方法存入文件
        try {
            props.store(new FileOutputStream("user.properties"), "");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
